import { ipcMain } from 'electron';
import { getInstalledApps, searchInstalledApps } from './index';

let appsCache: Awaited<ReturnType<typeof getInstalledApps>> = [];

// 初始化时加载软件列表
export async function initApps () {
  try {
    appsCache = await getInstalledApps(true); // 初始化时强制刷新，获取最新列表
  } catch (error) {
    console.error('init apps error:', error);
    appsCache = [];
  }
}

// 注册 IPC 处理器
export function register () {
  // 获取已安装软件列表
  ipcMain.handle('getInstalledApps', async (_event, forceRefresh = false) => {
    if (forceRefresh || appsCache.length === 0) {
      appsCache = await getInstalledApps(forceRefresh);
    }
    return appsCache;
  });

  // 搜索已安装软件
  ipcMain.handle('searchInstalledApps', async (_event, keyword: string) => {
    if (appsCache.length === 0) {
      appsCache = await getInstalledApps();
    }
    return searchInstalledApps(appsCache, keyword);
  });
}

